package com.example.compreshensiveshop.controller.job;

import com.example.compreshensiveshop.po.ItemPO;
import com.example.compreshensiveshop.service.ItemService;
import com.example.compreshensiveshop.service.OrdersService;
import com.example.compreshensiveshop.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class TimeoutOrderJob {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private ProductService productService;
    @Scheduled(cron = "0 0/20 * * * ?")
    public void exec(){
try{
log.info("定时任务开始执行：开始查找超时订单");
    List<Long> orderIds = ordersService.queryTimeoutOrders();
    for (Long orderId : orderIds) {
        log.info("处理超时订单，订单号：{}", orderId);
        List<ItemPO> itemPOs = itemService.queryByOId(orderId);
        ordersService.closeOrder(orderId);
        for (ItemPO itemPO : itemPOs) {
            log.info("处理订单项，订单项ID：{}", itemPO.getId());
            itemService.updateItemStatus(itemPO.getId(),3);
            productService.backStock(itemPO.getSkuId(), itemPO.getQuantity());
        }
    }
}catch (Exception e){
    log.error("定时任务执行异常",e);
}
    }
}
